package com.pointi.emoClientM;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.pointi.emoTools.DefineParam;
import com.pointi.emoTools.WorkList;
import com.pointi.emoTools.emoLogManager;

public class emoClient
{
	public static void main (String [] args) throws Exception
	{
		CheckStatus _Status = null ;
		int managerLimit = 0 ;
		int managerCount = 0 ;
		
		// ____________________________________________________________________________________________________
		// Read Configuration Data | Get ServerNo

		String str_conffile = "emoClientM.conf";
		ConfigurationData conf_data = new ConfigurationData();
		conf_data.InitializeData();
		try
		{
			conf_data = conf_data.ReadConfXML(str_conffile);
			conf_data.WriteLogConfigurationData(conf_data);
		}
		catch (Exception e)
		{
			System.out.println("[EM][CRT] Can't Read XML File!! - "+str_conffile);
			e.printStackTrace();
		}
		_Status = new CheckStatus(conf_data.s_client_no, conf_data.s_check_interval) ;
		
		// ____________________________________________________________________________________________________
		// JDBC | Connect Database

		JDBC jdbc = new JDBC() ;
		jdbc.SetDatabaseParam(conf_data) ;
		DefineParam define = new DefineParam();
		int nRet = define.DB_CONNECT_FAIL ;
		while (true) 
		{
			nRet = jdbc.fnConnectDB();
			if (nRet == define.DB_CONNECT_SUCCESS) break;
			System.out.println("[EM][CRT] Record DB Connect - "+nRet);
			Thread.sleep(1000);
		}

		// ____________________________________________________________________________________________________
		// Emotion Client LifeCycle

		ArrayList<WorkList> _WorkList = new ArrayList<WorkList>() ;
		ConcurrentLinkedQueue<ThreadWorkManager> _WorkManager = new ConcurrentLinkedQueue<ThreadWorkManager>() ; 
		ConcurrentLinkedQueue<ThreadStatusChecker> _StatusChecker = new ConcurrentLinkedQueue<ThreadStatusChecker>() ; 
		managerLimit = Integer.valueOf(conf_data.s_manager_limit) ;
		managerCount = 0 ;
		boolean loopHandlerA = true ;
		while(loopHandlerA)
		{
			// ____________________________________________________________________________________________________
			// Work Manager

			if (_WorkManager.isEmpty())
				_WorkManager = new ConcurrentLinkedQueue<ThreadWorkManager>() ;
			managerCount = _WorkManager.size() ;
			if (managerCount < managerLimit)
				new ThreadWorkManager(_WorkManager).start(conf_data, jdbc, _WorkList, _Status) ;

			// ____________________________________________________________________________________________________
			// Check Me(Client Status)
			
			if (_StatusChecker.isEmpty())
				_StatusChecker = new ConcurrentLinkedQueue<ThreadStatusChecker>() ;
			managerCount = _StatusChecker.size() ;
			if (managerCount < managerLimit)
				new ThreadStatusChecker(_StatusChecker).start(jdbc, _Status) ;
		}
		emoLogManager.mLog("[EM][CRT] END") ;
	}
}
